package com.net.xpay.admin.controller.admin;

import com.google.common.base.Preconditions;
import com.net.common.dao.OrderCondition;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultPagedList;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.AccountLog;
import com.net.xpay.core.enums.AccountFundType;
import com.net.xpay.core.manager.AccountLogManager;
import com.net.xpay.core.model.AccountLogSearchModel;
import com.net.shard.ShardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 */
@RestController
@Slf4j
@RequestMapping("/admin/account-log")
@Api(tags = "后台/服务费明细", description = "后台 服务费明细")
public class AdminAccountLogController {

    @Autowired
    private AccountLogManager accountLogManager;

    @Autowired
    private UserShardManager userShardManager;

    /**
     * 分页
     */
    @ApiOperation("分页")
    @PostMapping("/search")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'account-log::search')")
    public ResultPagedList<AccountLog> search(@RequestBody AccountLogSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        if (searchModel.getUserId() == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "商户编号必传");
        }

        UserShard userShard = userShardManager.getById(searchModel.getUserId());
        if (userShard == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "商户不存在");
        }

        try {
            ShardUtil.setShardContext(userShard.getShardId());

            searchModel.setUserId(searchModel.getUserId());
            searchModel.setAccountFundType(AccountFundType.MONEY);
            searchModel.setColumn("create_time");
            searchModel.setOrderby(OrderCondition.ORDER_BY_DESC);
            List<AccountLog> records = accountLogManager.search(searchModel);
            long count = accountLogManager.searchCount(searchModel);

            return new ResultPagedList<>(records, count, searchModel);
        } finally {
            ShardUtil.cleanShardContext();
        }
    }




}
